<template>
  <div class="hello">
    <el-upload
      class="upload-demo"
      action
      :http-request="handleUpload"
      :before-upload="beforeUpload"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <div v-for="(item, index) in fileList" :key="index">
      <img :src="item.url" alt="" /><button @click="delOssFile(item.name)">
        删除
      </button>
    </div>
  </div>
</template>

<script>
import { put, signatureUrl, getFileNameUUID, list, del } from "@/utils/oss.js";

export default {
  name: "visitStatistics",
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    beforeUpload(file) {
      return true;
    },
    /**
     * 自定义上传方法
     */
    async handleUpload(option) {
      // // 获取文件的后缀名
      var obj = option.file.name;
      var index = obj.lastIndexOf(".");
      obj = obj.substring(index, obj.length);
      // 生成的文件名，保留文件后缀名，进行拼接
      let objName = getFileNameUUID() + option.file.name;
      // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
      await put(`flieName/${objName}`, option.file).then((res) => {
        console.log(res);
        // 上传成功之后，转换真实的地址
        signatureUrl(`flieName/${objName}`).then((res) => {
          console.log(res);
        });
      });
      this.getOssFile();
    },
    async getOssFile() {
      const res = await list();
      this.fileList = res.objects;
      this.fileList.sort((a, b) => {
        return new Date(b.lastModified) - new Date(a.lastModified);
      });
      console.log(res);
    },
    async delOssFile(name) {
      await del(name);
      this.getOssFile();
    },
  },
  created() {
    this.getOssFile();
    // del();
  },
};
</script>
